package com.only4play.practice.pay.payment.core.controller;

import com.only4play.codegen.support.exception.BusinessException;
import com.only4play.codegen.support.model.JsonObject;
import com.only4play.practice.pay.payment.kit.CashierSupport;
import com.only4play.practice.pay.payment.kit.request.PayParamRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author mengdy
 */
@RestController
@RequestMapping("/pay")
@Slf4j
@RequiredArgsConstructor
public class PaymentController {

    private final CashierSupport cashierSupport;
    /**
     * 统一下单请求
     */
    @RequestMapping("callPayment")
    public JsonObject<Object> payment(
            HttpServletRequest request,
            HttpServletResponse response,
            @Validated @RequestBody PayParamRequest payParam) {
        try {
            return cashierSupport.payment(request, response, payParam);
        } catch (BusinessException se) {
            log.info("支付异常", se);
        } catch (Exception e) {
            log.error("收银台支付错误", e);
        }

        return null;
    }

    /**
     * <a href="https://opendocs.alipay.com/open/194/103296?pathHash=e43f422e">支付宝异步通知说明</a>
     * @param params 支付宝通过 POST 请求的形式将支付结果作为参数通知到商家系统
     */
    @RequestMapping("callback/{channelType}/{outTradeOrderNo}")
    public String callback(HttpServletRequest request,
                                       @PathVariable String channelType,
                                       @PathVariable String outTradeOrderNo,
                                       @RequestParam Map<String, String> params) {

        return cashierSupport.unifiedCallback(request,channelType,outTradeOrderNo,params);
    }
}
